package com.syj.usepagehelper.config;

import com.syj.usepagehelper.model.vo.response.EnumCommon;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.Log;
import java.util.Arrays;

/**
 * - All rights Reserved, Designed By ShiYunJie
 * - @Package com.newland.common.util
 * - @author: 石蕴杰
 * - @date:   2020/1/16 10:17
 * - @version V1.0
 * - @Copyright: Inc. All rights reserved.
 */
@Slf4j
public class MybatisLog implements Log {

    private String sql;

    public MybatisLog(String clazz) {
    }

    @Override
    public boolean isDebugEnabled() {
        return true;
    }

    @Override
    public boolean isTraceEnabled() {
        return true;
    }

    @Override
    public void error(String s, Throwable e) {
        log.error(s);
        e.printStackTrace(System.err);
    }

    @Override
    public void error(String s) {
        log.error(s);
    }

    @Override
    public void debug(String s) {
        if(s!=null&&s.contains(EnumCommon.MYBATIS_PREPARING.getCode()))
        {
            sql = s.replace("Preparing:","").replace("==>","");
        }else if(s!=null&&s.contains(EnumCommon.MYBATIS_PARAMETERS.getCode()))
        {
            String[] params = s.replace("==> Parameters: ","").split(",");
            Arrays.stream(params).forEach(param->{
                int index = param.indexOf("(");
                try{
                    if (index!=-1)
                    {
                       sql = sql.replaceFirst("[?]","'"+param.substring(0,index).trim()+"'");
                    }
                }catch (Exception e)
                {
                    e.printStackTrace();
                }
            });
            log.info("MyBatis sql:\n"+sql);
        }
    }

    @Override
    public void trace(String s) {
//        log.info(s);
    }

    @Override
    public void warn(String s) {
//        log.info(s);
    }
}
